import os
import argparse
import cv2
from utils import get_file_in_dir


if __name__ == '__main__':
    parser = argparse.ArgumentParser("convert pictures to video", add_help=True)
    parser.add_argument(
        "--input_dir", "-i", type=str, required=True, help="input directory"
    )
    parser.add_argument(
        "--output_dir", "-o", type=str, default="./outputs", help="output directory"
    )
    parser.add_argument(
        "--fps", "-f", type=float, default=10.0, help="frame rate"
    )
    args = parser.parse_args()
    os.makedirs(args.output_dir, exist_ok=True)

    image_paths = get_file_in_dir(args.input_dir, '.png')
    if len(image_paths) == 0:
        print("No image found in input directory")
        exit(1)

    image_paths.sort()

    video_name = "output_video.mp4"   # Output video name

    # Read first image to get dimensions
    frame = cv2.imread(image_paths[0], cv2.IMREAD_UNCHANGED)
    height, width = frame.shape[0], frame.shape[1]

    # Create video writer object
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Codec format
    video = cv2.VideoWriter(os.path.join(args.output_dir, video_name), fourcc, args.fps, (width, height))

    # Write frames sequentially
    for image_path in image_paths:
        image = cv2.imread(image_path)
        video.write(image)

    # Release resources
    video.release()
